<?

class plugin_install_task extends system_task
{
	public function execute( array $params = array() )
	{
		if ( !$this->plugin = $params[0] ) return $this->error('Provide plugin name');

		$plugins_folder = realpath(dirname(__FILE__) . '/../../../assets/generate/plugins');

		$plugin_path = $plugins_folder . '/' . $this->plugin;
		if ( !is_dir($plugin_path) ) return $this->error('Plugin not found');

		$this->out('Installing plugin: ' . $this->plugin);
		$this->copy_dir($plugin_path, getcwd());

		$this->out('Migrating data...');
		$task = new db_migrate_task( $this->output );
		$task->execute();
	}

	protected function copy_dir( $src, $dst )
	{
		$d = opendir($src);
		while ( $f = readdir($d) )
		{
			if ( in_array($f, array('.', '..', '.svn')) ) continue;

			$path = $src . '/' . $f;
			$this->out('-' . $f);

			if ( is_dir($path) )
			{
				if ( !is_dir($dst . '/' . $f) ) mkdir($dst . '/' . $f);
				$this->copy_dir($path, $dst . '/' . $f);
			}
			else
			{
				if (file_exists($dst . '/' . $f) )
					return $this->error ('Seems like plugin already installed, found: ' . $dst . '/' . $f);

				$content = file_get_contents($path);
				file_put_contents($dst . '/' . $f, $content);
			}
		}
	}
}